package com.crowntit.domain.activity.service;

import com.alibaba.fastjson.JSON;
import com.crowntit.domain.activity.adapter.repository.IActivityRepository;
import com.crowntit.domain.activity.model.entity.*;
import com.crowntit.domain.activity.service.trail.factory.DefaultActivityStrategyFactory;
import com.crowntit.types.design.framework.tree.StrategyHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class IndexGroupBuyMarketServiceImpl implements IIndexGroupBuyMarketService{

    @Resource
    private IActivityRepository activityRepository;

    @Resource
    private DefaultActivityStrategyFactory defaultActivityStrategyFactory;

    @Override
    public TrialBalanceEntity indexMarketTrial(MarketProductEntity productEntity) throws Exception {
        StrategyHandler<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> strategyHandler = defaultActivityStrategyFactory.strategyHandler();

        TrialBalanceEntity trialBalanceEntity = strategyHandler.apply(productEntity, DefaultActivityStrategyFactory.DynamicContext.builder().build());

        return trialBalanceEntity;
    }

    @Override
    public SkuActivityEntity queryScSkuInfo(ScSkuEntity scSkuEntity) {
        return activityRepository.querySkuConfig(scSkuEntity);
    }

    @Override
    public List<UserGroupBuyTeamDetailEntity> queryInProgressTeam(IndexTeamQueryEntity queryEntity) {
        List<UserGroupBuyTeamDetailEntity> teamList = new ArrayList<>();

        UserGroupBuyTeamDetailEntity userGroupBuyTeamDetailEntity = activityRepository.queryGroupBuyTeamDetailByUser(queryEntity);
        if (userGroupBuyTeamDetailEntity != null) {
            queryEntity.setTeamIdUserIn(userGroupBuyTeamDetailEntity.getTeamId());
            teamList.add(userGroupBuyTeamDetailEntity);
        }

        List<UserGroupBuyTeamDetailEntity> userGroupBuyTeamDetailEntities = activityRepository.queryIndexTeamList(queryEntity);
        if (userGroupBuyTeamDetailEntities != null && !userGroupBuyTeamDetailEntities.isEmpty())
            teamList.addAll(userGroupBuyTeamDetailEntities);

        log.info("查询商品相关组队信息；用户所在拼团: {} \n 系统中正在进行的拼团: {}", JSON.toJSONString(userGroupBuyTeamDetailEntity), JSON.toJSONString(userGroupBuyTeamDetailEntities));
        return teamList;
    }
}
